package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

// 通过这个类, 来处理 /blog 路径对应的请求
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    // 这个方法有两个用处:
    //如果请求中有blogId,就获取博客详细
    //如果没有,就获取博客列表

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao = new BlogDao();
        resp.setContentType("application/json; charset=utf8");

        // 先尝试获取到 req 中的 blogId 参数. 如果该参数存在, 说明是要请求博客详情
        String param = req.getParameter("blogId");
        if (param == null){
            //不存在就从数据库中获取博客列表，转成JSON格式返回即可
            List<Blog> blogs = blogDao.selectAll();
            //把blogs转成JSON格式
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(respJson);
        }else {
            // 存在参数, 获取博客详情
            int blogId = Integer.parseInt(param);
            Blog blog = blogDao.selectOne(blogId);
            String respJson = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(respJson);
        }
    }

    //提交博客
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 要先指定好请求按照哪种编码来解析
        req.setCharacterEncoding("utf8");

        // 博客的标题和正文上传
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || "".equals(title) || content == null || "".equals(content)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("提交博客失败，缺少参数");
            return;
        }

        // 构造 Blog对象，把当前信息填进去，并插入数据库中
        // 这里的重点是userId要通过会话获取
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        //通过这个会话就可以获取usrId
        User user = (User)session.getAttribute("user");

        //构造一个博客对象，插入到数据库中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

        //最后重定向
        resp.sendRedirect("blog_list.html");

        //因为是post请求，这里用form表单来提交
    }
}
